import axios from 'axios'
import {ElMessage} from 'element-plus'
import {getToken} from "@/util/auth.js";
import {useUserStore} from "@/stores/user/index.js";
// 创建axios实例
const request = axios.create({
    // 这里可以放一下公用属性等。
    baseURL: import.meta.env.VITE_APP_BASE_API,
    withCredentials: false, // 跨域请求时是否需要访问凭证
    timeout: 10 * 1000, // 请求超时时间
})
// 存储正在进行的请求
const pendingRequests = new Map();
// 生成请求唯一标识
const generateReqKey = (config) => {
    const { method, url, params, data } = config;
    return [method, url, JSON.stringify(params), JSON.stringify(data)].join('&');
};
// 请求拦截器
request.interceptors.request.use((config) => {
    if  (config.method !== 'get') {
        const requestKey = generateReqKey(config);
        // 检查是否已有相同请求在进行中
        if (pendingRequests.has(requestKey)) {
            const cancelToken = pendingRequests.get(requestKey);
            cancelToken('取消重复请求');
        }
        // 为当前请求创建取消令牌
        config.cancelToken = new axios.CancelToken(cancel => {
            pendingRequests.set(requestKey, cancel);
        });
    }
    if (getToken()) {
        config.headers['Authorization'] = 'Bearer ' + getToken();
    }
    config.headers['Content-type'] = 'application/json';
    return config;
}, (error) => {
    return Promise.reject(error)
})

request.interceptors.response.use((response) => {
    //如果是下载请求，保留  headers信息
    if (response.config.responseType === 'blob') {
        return response; //  保留 headers
    }
    let {code, msg} = response.data
    switch (code) {
        case 401:
            const userStore = useUserStore()
            ElMessage({message: msg, type: 'error'})
            if (getToken()) {
                userStore.logout()
            }
            break
        case 200:
            if (response.config.method !== 'get') {
                ElMessage({message: msg, type: 'success'})
            }
            break
        default:
            ElMessage({message: msg, type: 'error'})
    }
    return response.data;
}, (error) => {
    if (axios.isCancel(error)) {
        // 如果是取消的重复请求，不显示错误
        console.log('重复请求已取消:', error.message);
        return Promise.reject({ isCanceled: true });
    }
    const requestKey = generateReqKey(error.config);
    if (pendingRequests.has(requestKey)) {
        pendingRequests.delete(requestKey);
    }
    ElMessage.error(error.message || '请求失败');
    return Promise.reject(error)
})

export default request;
